/*
 * Copyright 2011-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package xyz.ewangshi.jdbc;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

/**
 * @author ewangshi
 * 2016-07-06
 */
public class JDBC {
	
	public static void main(String[] args) {
		@SuppressWarnings("resource")
		ApplicationContext context = new ClassPathXmlApplicationContext("xyz/ewangshi/jdbc/applicationContext.xml");
		NamedParameterJdbcTemplate jdbcTemplate = (NamedParameterJdbcTemplate) context.getBean("namedParameterJdbcTemplate");
		String sql = "select id,name,length,width,height,price,create_time,is_del from product";
		
		int count = 0;
		long a = System.currentTimeMillis();
		
		for (int i = 0; i < count; i++) {
			jdbcTemplate.queryForList(sql, new HashMap<String, String>());
		}
		
		long b = System.currentTimeMillis();
		
		for (int i = 0; i < count; i++) {
			jdbcTemplate.query(sql, new HashMap<String, String>(), new BeanPropertyRowMapper<Product>(Product.class));
		}
		
		long c = System.currentTimeMillis();
		
		for (int i = 0; i < count; i++) {
			jdbcTemplate.query(sql, new HashMap<String, String>(), new Product());
		}
		
		long d = System.currentTimeMillis();
		
		System.out.println(b - a);
		System.out.println(c - b);
		System.out.println(d - c);
		
		
		SQLSupport sqlSupport = new SQLSupport();
		sqlSupport.setNamedParameterJdbcTemplate(jdbcTemplate);
		Map<String, String> map = new HashMap<>();
		map.put("id", "2");
		List<Product> ps = sqlSupport.query("test", map, new Product());
		System.out.println(ps);
		
		Map<String, Object> upParamMap = new HashMap<>();
		upParamMap.put("id", "2");
		upParamMap.put("name", "newName2");
		upParamMap.put("is_del", 1);
		upParamMap.put("haha", 1);
		sqlSupport.update("update", upParamMap);
		
		Map<String, Object> delParamMap = new HashMap<>();
		delParamMap.put("id", "3");
		sqlSupport.update("delete", delParamMap);
		
		Map<String, Object> insertParamMap = new HashMap<>();
		insertParamMap.put("name", "xxx");
		insertParamMap.put("is_del", "0");
		insertParamMap.put("create_time", new Date());
		sqlSupport.insert("insert",insertParamMap);
		
	}
}
